package com.bac.rentmap.ad.publisher;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.beans.factory.annotation.Required;

import com.bac.rentmap.ad.flat.proccess.FlatAdProccessor;
import com.bac.rentmap.jdo.JdoSupport;

/**
 * Decreases <code>adCount</code> for {@link AdPublisher} s with
 * <code>lastPublishingDate</code> older than <code>maxAgeInDays</code>. If some
 * {@link AdPublisher} has <code>lastPublishingDate = 0</code> after this
 * operation then he is removed. By default maxAgeInDays is configured to
 * process all {@link AdPublisher} s.
 *
 * @author Andrew Osipenko
 */
public class OldAdPublisherBatchProccessor extends JdoSupport implements
        FlatAdProccessor {
    private static final Logger log = Logger
            .getLogger(OldAdPublisherBatchProccessor.class.getName());

    private int batchSize;
    private Integer maxAgeInDays = -1;

    public int proccess() throws IOException {
        PersistenceManager persistenceManager = getPersistenceManager();
        try {
            Calendar calendar = GregorianCalendar.getInstance();
            calendar.add(Calendar.DATE, -maxAgeInDays);

            Query query = persistenceManager.newQuery(AdPublisher.class);
            query.setRange(0, batchSize);
            query.setFilter("lastPublishingDate < publishingDateParam");
            query.declareParameters("java.util.Date publishingDateParam");
            @SuppressWarnings("unchecked")
			List<AdPublisher> res = (List<AdPublisher>) query.execute(calendar
                    .getTime());
            log.info("Found " + res.size() + " old ad publishers");
            for (AdPublisher adPublisher : res) {
                if (adPublisher.getAdCount() <= 1) {
                    persistenceManager.deletePersistent(adPublisher);
                } else {
                    adPublisher.setAdCount(adPublisher.getAdCount() - 1);
                }
            }
            return res.size();
        } finally {
            persistenceManager.close();
        }
    }

    @Required
    public void setBatchSize(int batchSize) {
        this.batchSize = batchSize;
    }

    public void setMaxAgeInDays(Integer maxAgeInDays) {
        this.maxAgeInDays = maxAgeInDays;
    }
    public int getQueueSize() {
        return -1;
    }
    public int getBatchSize() {
        return batchSize;
    }
}
